﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Mvc;
using System.IO;
using System.Web.Security;

namespace Fx.Mvc
{
    public class BaseController : Controller
    {
        protected override void OnAuthorization(AuthorizationContext filterContext)
        {
            var checkInDatabase = true;
            if (Request.IsAuthenticated)
            {
                var cookie = CookieAuthentication.GetTokenFromCookie();
                if (cookie != null && checkInDatabase)
                {
                    var token = CookieAuthentication.GetTokenFromDatabase(cookie.Value);
                    if (token == null)
                    {
                        FormsAuthentication.SignOut();
                        FormsAuthentication.RedirectToLoginPage();
                    }
                }
            }
            base.OnAuthorization(filterContext);
        }

        protected ActionResult JsonView(string viewName, object model)
        {
            var viewString = this.StringView(viewName, model);
            return Json(new { Result = true, View = viewString });
        }
    }

    public static class ControllerExtensions
    {
        /// <summary>
        /// Renders a (partial) view to string.
        /// </summary>
        /// <param name="controller">Controller to extend</param>
        /// <param name="viewName">(Partial) view to render</param>
        /// <param name="model">Model</param>
        /// <returns>Rendered (partial) view as string</returns>
        public static string StringView(this Controller controller, string viewName, object model)
        {
            if (string.IsNullOrEmpty(viewName))
                viewName = controller.ControllerContext.RouteData.GetRequiredString("action");

            controller.ViewData.Model = model;

            using (var sw = new StringWriter())
            {
                var viewResult = ViewEngines.Engines.FindPartialView(controller.ControllerContext, viewName);
                var viewContext = new ViewContext(controller.ControllerContext, viewResult.View, controller.ViewData, controller.TempData, sw);
                viewResult.View.Render(viewContext, sw);

                return sw.GetStringBuilder().ToString();
            }
        }
    }
}
